import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import prisma from '@/lib/db';

export async function GET(request: NextRequest) {
  try {
    const session = await auth();
    
    // 检查用户是否已登录
    if (!session?.user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const userId = session.user.id;
    
    // 获取用户基本信息
    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: {
        id: true,
        name: true,
        email: true,
        image: true,
        createdAt: true,
      }
    });

    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 获取用户资料
    const profile = await prisma.userProfile.findUnique({
      where: { userId },
      select: {
        bio: true,
        jobTitle: true,
        location: true,
        skills: true,
        socialLinks: true,
      }
    });

    // 组合返回数据
    const responseData = {
      ...user,
      ...profile,
      joinedAt: user.createdAt,
      bio: profile?.bio || '',
      jobTitle: profile?.jobTitle || '',
      location: profile?.location || '',
      skills: profile?.skills || [],
      socialLinks: profile?.socialLinks || {},
    };

    return NextResponse.json(responseData);
  } catch (error) {
    console.error('获取用户资料失败:', error);
    return NextResponse.json(
      { error: '获取用户资料失败' },
      { status: 500 }
    );
  }
}

export async function PATCH(request: NextRequest) {
  try {
    console.log('【API】接收用户资料更新请求');
    const session = await auth();
    
    // 检查用户是否已登录
    if (!session?.user) {
      console.log('【API错误】未授权访问 - 用户未登录');
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const userId = session.user.id;
    console.log(`【API】用户资料更新 - 用户ID: ${userId}`);
    
    // 解析请求数据
    let data;
    try {
      data = await request.json();
      console.log('【API】用户资料更新 - 接收数据:', data);
    } catch (parseError) {
      console.error('【API错误】解析请求数据失败:', parseError);
      return NextResponse.json(
        { error: '无效的请求数据格式', details: parseError instanceof Error ? parseError.message : String(parseError) },
        { status: 400 }
      );
    }
    
    // 验证数据
    if (!data || typeof data !== 'object') {
      console.error('【API错误】请求数据无效 - 不是对象');
      return NextResponse.json(
        { error: '无效的请求数据' },
        { status: 400 }
      );
    }
    
    const validUserFields = ['name'];
    const validProfileFields = ['bio', 'jobTitle', 'location', 'skills', 'socialLinks'];
    
    // 分离用户表和用户资料表的字段
    const userUpdateData = Object.keys(data)
      .filter(key => validUserFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);
    
    const profileUpdateData = Object.keys(data)
      .filter(key => validProfileFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);
    
    console.log('【API】用户资料更新 - 处理后数据:', { userUpdateData, profileUpdateData });

    try {
      // 开始事务，同时更新用户和用户资料
      const [updatedUser, updatedProfile] = await prisma.$transaction([
        // 更新用户基本信息
        prisma.user.update({
          where: { id: userId },
          data: userUpdateData,
          select: {
            id: true,
            name: true,
            email: true,
            image: true,
            createdAt: true,
          }
        }),
        
        // 更新或创建用户资料
        prisma.userProfile.upsert({
          where: { userId },
          update: profileUpdateData,
          create: {
            userId,
            ...profileUpdateData,
          },
          select: {
            bio: true,
            jobTitle: true,
            location: true,
            skills: true,
            socialLinks: true,
          }
        })
      ]);

      // 组合返回数据
      const responseData = {
        ...updatedUser,
        ...updatedProfile,
        joinedAt: updatedUser.createdAt,
      };
      
      console.log('【API】用户资料更新成功');
      return NextResponse.json(responseData);
    } catch (dbError) {
      console.error('【API错误】数据库操作失败:', dbError);
      return NextResponse.json(
        { error: '更新用户资料失败', details: dbError instanceof Error ? dbError.message : String(dbError) },
        { status: 500 }
      );
    }
  } catch (error) {
    console.error('【API错误】更新用户资料失败:', error);
    return NextResponse.json(
      { error: '更新用户资料失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    const session = await auth();
    
    // 检查用户是否已登录
    if (!session?.user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const userId = session.user.id;
    const data = await request.json();
    
    // 验证数据
    const validUserFields = ['name'];
    const validProfileFields = ['bio', 'jobTitle', 'location', 'skills', 'socialLinks'];
    
    // 分离用户表和用户资料表的字段
    const userUpdateData = Object.keys(data)
      .filter(key => validUserFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);
    
    const profileUpdateData = Object.keys(data)
      .filter(key => validProfileFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);

    // 开始事务，同时更新用户和用户资料
    const [updatedUser, updatedProfile] = await prisma.$transaction([
      // 更新用户基本信息
      prisma.user.update({
        where: { id: userId },
        data: userUpdateData,
        select: {
          id: true,
          name: true,
          email: true,
          image: true,
          createdAt: true,
        }
      }),
      
      // 更新或创建用户资料
      prisma.userProfile.upsert({
        where: { userId },
        update: profileUpdateData,
        create: {
          userId,
          ...profileUpdateData,
        },
        select: {
          bio: true,
          jobTitle: true,
          location: true,
          skills: true,
          socialLinks: true,
        }
      })
    ]);

    // 组合返回数据
    const responseData = {
      ...updatedUser,
      ...updatedProfile,
      joinedAt: updatedUser.createdAt,
    };

    return NextResponse.json(responseData);
  } catch (error) {
    console.error('更新用户资料失败:', error);
    return NextResponse.json(
      { error: '更新用户资料失败' },
      { status: 500 }
    );
  }
} 